﻿using System;
using System.Net;

namespace Ayatta.Common.Extension
{
    public static class IpAddressExtension
    {
        /// <summary>
        /// 获得IP转换后的数字（支持IP4）
        /// </summary>
        /// <param name="address">0x2414188f->143.24.20.36</param>
        /// <returns>605296783</returns>
        public static long ToLong(this IPAddress address)
        {
            if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
            {
                return 0;
            }

            switch (address.GetAddressBytes().Length)
            {
                case 4:
                    return BitConverter.ToUInt32(address.GetAddressBytes(), 0);
                case 8:
                    return (long)BitConverter.ToUInt64(address.GetAddressBytes(), 0);
                default:
                    throw new Exception("Invalid IPv4 Address passed, length not 4 or 8 bytes");
            }
        }
    }
}